<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
	<head>
		<title>Model List Cookie Demo</title>
        <style type='text/css'>
            body {font-family: verdana}
            li {border: solid 1px gray; padding: 5px; width: 250px;}
			li a {color: red; font-weight: bold;}
			p {width: 400px;}
        </style>
	</head>
	<body>
		<div id="demo-instructions">
			<h1>Cookie List Demo</h1>
			<p>This demo show keeping data stored in a cookie.  Create a few contacts,
			refresh the page, and they should still be present.</p>
		</div>
<div id="demo-html">
<h2>Create A Contact</h2>
<form action='' id='contact'>
	<label>Name</label> 
	<input type='text' name='name'/> <br/>
	<label>Birthday</label> 
	<input type='text' name='birthday' value='1982-10-20'/> 
	(must be like 1982-10-20)<br/>
	<input type='submit' value='Create' />
</form>
<h2>List of Contacts</h2>
<div id='contacts'></div>
</div>
		
<script type='text/javascript' 
        src='../../../../steal/steal.js'>   
</script>
<script type='text/javascript'>
steal('jquery/model',
		'jquery/model/list/cookie',
		'jquery/dom/form_params').then(function(){
			
$.Model("Contact",{
	attributes : { 
		birthday : 'date'
	},
	convert : {
		date : function(raw){
			if(typeof raw == 'string'){
				var matches = raw.match(/(\d+)-(\d+)-(\d+)/)
				return new Date( +matches[1], 
				                 (+matches[2])-1, 
				                 +matches[3] )
			}else if(raw instanceof Date){
				return raw;
			}
		}
	}
},{
	ageThisYear : function(){
		return new Date().getFullYear() - 
		      this.birthday.getFullYear()
	},
	getBirthday : function(){
		return ""+this.birthday.getFullYear()+
			"-"+(this.birthday.getMonth()+1)+
			"-"+this.birthday.getDate();
	}

});

// Create a contact list
$.Model.List.Cookie("Contact.List");

// A helper function for adding a contact to the page
var addContact = function(contact){
	 var li = $('<li>')
              .model(contact)
              .html(contact.name+" "+contact.ageThisYear())
              .appendTo($("#contacts"));
}
$(function(){
	// pull saved contacts into this list
	var contacts = new Contact.List([]).retrieve("contacts");
	
	// add each contact to the page
	contacts.each(function(){
		addContact(this);
	});
	
	// when a new cookie is crated
	$("#contact").submit(function(ev){
		ev.preventDefault();
		var data = $(this).formParams();
		
		// gives it a random id
		data.id = +new Date();
		var contact = new Contact(data);
		
		//add it to the list of contacts 
		contacts.push(contact);
		
		//store the current list
		contacts.store("contacts");
		
		//show the contact
		addContact(contact);
	})
})
})

</script>
	</body>
</html>